#include "EventString.h"

#include "EventObject.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct _EventString
{
	EventObject parent_instance;

	char *string;
	int   length;
};

static void
event_string_finalize(EventString *self)
{
	if (self->string)
		free(self->string);
}

EventString *
event_string_new(const char *string)
{
	EventString *object = MALLOC_NEW(EventString);

	event_object_init(EVENT_OBJECT(object));
	event_object_set_finalize(object, FINALIZE(event_string_finalize));

	object->length = strlen(string);
	object->string = (char *)malloc(object->length + 1);
	strcpy(object->string, string);

	return object;
}

EventString *
event_string_new_with_size(const epointer raw, int size)
{
	EventString *object = MALLOC_NEW(EventString);

	event_object_init(EVENT_OBJECT(object));
	event_object_set_finalize(object, FINALIZE(event_string_finalize));

	object->length	     = size;
	object->string	     = (char *)malloc(size + 1);
	object->string[size] = '\0';
	if (size > 0)
		memcpy(object->string, raw, size);

	return object;
}

const char *
event_string_get_string(const EventString *self)
{
	return_val_if_fail(self != NULL, event_string_get_string, NULL);

	return self->string;
}

int
event_string_get_length(const EventString *self)
{
	return_val_if_fail(self != NULL, event_string_get_length, 0);
	return self->length;
}

bool
event_string_compare(const EventString *str1, const EventString *str2)
{
	return_val_if_fail((str1 != NULL && str2 != NULL), event_string_compare,
			   false);
	return (strcmp(str1->string, str2->string) == 0);
}

void
event_string_append(EventString *self, const char *child_str)
{
	static char *cache;
	return_if_fail(self != NULL, event_string_append);

	self->length += strlen(child_str);
	cache	      = (char *)malloc(self->length + 1);
	strcpy(cache, self->string);
	free(self->string);
	strcat(cache, child_str);
	self->string = cache;
}

EventString *
event_string_copy_append(EventString *self, const char *child_str)
{
	EventString *string;
	return_val_if_fail(self != NULL, event_string_copy_append, NULL);

	string = event_string_new(self->string);
	event_string_append(string, child_str);
	return string;
}
